<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>{{{ PRODUCT_NAME }}}</title>
    <link rel="shortcut icon" href="TemplateData/favicon.ico">
    <link rel="stylesheet" href="TemplateData/style.css">
	<script src="js/aframe.min.js"></script>
    <script src="js/aframe-ar.js"></script>
  </head>
  <body style="margin: 0px; overflow: hidden;"> 
    <div id="unity-container" style="z-index: 2" >
      <canvas id="unity-canvas" width={{{ WIDTH }}} height={{{ HEIGHT }}}></canvas>
      <div id="unity-loading-bar">
        <div id="unity-logo"></div>
        <div id="unity-progress-bar-empty">
          <div id="unity-progress-bar-full"></div>
        </div>
      </div>
      <div id="unity-warning"> </div>
      <div id="unity-footer">
        <div id="unity-webgl-logo"></div>
        <div id="unity-fullscreen-button"></div>
        <div id="unity-build-title">{{{ PRODUCT_NAME }}}</div>
      </div>
    </div>
	<a-scene embedded arjs vr-mode-ui="enabled: false" copycanvas>
    <script>
      var container = document.querySelector("#unity-container");
      var canvas = document.querySelector("#unity-canvas");
      var loadingBar = document.querySelector("#unity-loading-bar");
      var progressBarFull = document.querySelector("#unity-progress-bar-full");
      var fullscreenButton = document.querySelector("#unity-fullscreen-button");
      var warningBanner = document.querySelector("#unity-warning");
 
      var buildUrl = "Build";
      var loaderUrl = buildUrl + "/{{{ LOADER_FILENAME }}}";
      var config = {
        dataUrl: buildUrl + "/{{{ DATA_FILENAME }}}",
        frameworkUrl: buildUrl + "/{{{ FRAMEWORK_FILENAME }}}",
#if USE_WASM
        codeUrl: buildUrl + "/{{{ CODE_FILENAME }}}",
#endif
#if MEMORY_FILENAME
        memoryUrl: buildUrl + "/{{{ MEMORY_FILENAME }}}",
#endif
#if SYMBOLS_FILENAME
        symbolsUrl: buildUrl + "/{{{ SYMBOLS_FILENAME }}}",
#endif
        streamingAssetsUrl: "StreamingAssets",
        companyName: {{{ JSON.stringify(COMPANY_NAME) }}},
        productName: {{{ JSON.stringify(PRODUCT_NAME) }}},
        productVersion: {{{ JSON.stringify(PRODUCT_VERSION) }}}, 
      };
 
        var meta = document.createElement('meta');
        meta.name = 'viewport';
        meta.content = 'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
        document.getElementsByTagName('head')[0].appendChild(meta);
        container.className = "unity-mobile";
        canvas.className = "unity-mobile";
   
      loadingBar.style.display = "block";

	  var myUnityInstance=null;
      var script = document.createElement("script");
      script.src = loaderUrl;
      script.onload = () => {
        createUnityInstance(canvas, config, (progress) => {
          progressBarFull.style.width = 100 * progress + "%";
        }).then((unityInstance) => {
		  myUnityInstance = unityInstance;
          loadingBar.style.display = "none";
          fullscreenButton.onclick = () => {
            unityInstance.SetFullscreen(1);
          };
        }).catch((message) => {
          alert(message);
        });
      };
      document.body.appendChild(script);
	  
	let isCameraReady = false;
	let isDetectionManagerReady = false;
	let gl = null;

	function cameraReady(){
		isCameraReady = true;
		gl = myUnityInstance.Module.ctx;
	}

	function detectionManagerReady(){
		isDetectionManagerReady = true;
	}

	function createUnityMatrix(el){
		const m = el.matrix.clone();
		const zFlipped = new THREE.Matrix4().makeScale(1, 1, -1).multiply(m);
		const rotated = zFlipped.multiply(new THREE.Matrix4().makeRotationX(-Math.PI/2));
		return rotated;
	}

	AFRAME.registerComponent('markercontroller', {
		schema: {
			name : {type: 'string'}
		},
		tock: function(time, timeDelta){

			let position = new THREE.Vector3();
			let rotation = new THREE.Quaternion();
			let scale = new THREE.Vector3();

			createUnityMatrix(this.el.object3D).decompose(position, rotation, scale);

			const serializedInfos = `${this.data.name},${this.el.object3D.visible},${position.toArray()},${rotation.toArray()},${scale.toArray()}`;

			if(isDetectionManagerReady){
			  myUnityInstance.SendMessage("DetectionManager", "markerInfos", serializedInfos);
			}
		} 
	});

	AFRAME.registerComponent('cameratransform', {
		tock: function(time, timeDelta){

			let camtr = new THREE.Vector3();
			let camro = new THREE.Quaternion();
			let camsc = new THREE.Vector3();

			this.el.object3D.matrix.clone().decompose(camtr, camro, camsc);

			const projection = this.el.components.camera.camera.projectionMatrix.clone();
			const serializedProj = `${[...projection.elements]}`

			const posCam = `${[...camtr.toArray()]}`
			const rotCam = `${[...camro.toArray()]}`
	 
			if(isCameraReady){
				myUnityInstance.SendMessage("Main Camera", "setProjection", serializedProj);
				myUnityInstance.SendMessage("Main Camera", "setPosition", posCam);
				myUnityInstance.SendMessage("Main Camera", "setRotation", rotCam);

				let w = window.innerWidth;
				let h = window.innerHeight; 

				const unityCanvas = document.querySelector("#unity-canvas");

				const ratio = unityCanvas.height / h;

				w *= ratio
				h *= ratio

				const size = `${w},${h}`

				myUnityInstance.SendMessage("Canvas", "setSize", size);
			}

			if(gl != null){
				gl.dontClearOnFrameStart = true;
			}
		} 
	});

	AFRAME.registerComponent('copycanvas', {
		tick: function(time, timeDelta){
			const unityCanvas = document.querySelector("#unity-canvas");
			unityCanvas.width = this.el.canvas.width
			unityCanvas.height = this.el.canvas.height
		} 
	});
    </script>
  --MARKERS--
      <a-entity camera cameratransform></a-entity>
    </a-scene>
  </body>
</html>
